package com.learn.sb.reids.demo.pubsub;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 订阅发布模式的 订阅者，可以起多个
 */
@SpringBootApplication
public class RedisSubscribeDemo {

	public static void main(String[] args) {
		SpringApplication.run(RedisSubscribeDemo.class, args);
	}

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;  // redis连接工厂
	@Autowired
	private MessageListener redisMessageListener;  // redis 监听器
	@Autowired
	private ThreadPoolTaskScheduler taskScheduler;  // 定时任务池

	@Bean
	public ThreadPoolTaskScheduler initTaskScheduler() {
		if (null != taskScheduler) {
			return taskScheduler;
		}
		taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(20);
		return taskScheduler;
	}

	@Bean
	public RedisMessageListenerContainer initRedisMessageListenerContainer() {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		// Redis 连接工厂
		container.setConnectionFactory(redisConnectionFactory);
		// 设置运行任务池
		container.setTaskExecutor(taskScheduler);
		// 定义监听渠道，名称为 topicA
		Topic topic = new ChannelTopic("topicA");
		// 使用监听器监听Redis消息
		container.addMessageListener(redisMessageListener, topic);

		return container;
	}
}
